'use strict'

let templateConfig = require('../config/templateConfig')

//多人场景
class Scene {
  constructor(templateId) {
    this.id = templateId
    this.clients = new Set()
  }

  addClient(session) {
    //离开原来的场景
    if (session.sceneId) {
      sceneMgr.getSceneSerById(session.sceneId).dropClient(session.id)
    }
    this.clients.add(session.id)
    session.sceneId = this.id
  }

  dropClient(sessionId) {
    this.clients.delete(sessionId)
  }

  getClientCnt() {
    return this.clients.size
  }

  getClients() {
    return this.clients
  }
}

//多人场景服务
class SceneMgr {
  constructor() {
    this.scenes = {}
    this.initScene()
  }

  //初始化所有的场景
  initScene() {
    for (let i in templateConfig.scene) {
      let scene = new Scene(i)
      this.addScene(scene)
    }
  }

  //添加一个场景服务器
  addScene(scene) {
    this.scenes[scene.id] = scene
  }

  //返回场景服务的实例
  getSceneSerById(sceneId) {
    return this.scenes[sceneId]
  }

  //获取公共场景中所有的客户端数量
  getAllClientCnt() {
    let total = 0
    for (let s of scenes) {
      total += s.getClientCnt()
    }
  }

  //删除该场景的客户
  dropClientToScene(sceneId, sessionId) {
    this.scenes[sceneId].dropClient(sessionId)
  }
}
let sceneMgr = new SceneMgr()
module.exports = sceneMgr
